/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**This Activity handles both
 * - creation of a Homescreen shortcut
 * - executing a shortcut
 * */
public class ShortCutHandler extends Activity {
	/**Bundle Extra used by a Shortcut*/	public static final String SHORTCUT_PROFILE_EXTRA_ID = "profID";
	/**Action used by a Shortcut*/			public static final String SHORTCUT_PROFILE_ACTION = "de.drak.Profiles.intent.action.LAUNCH";

    private Database mDbHelper;
    private AlertDialog mDialog;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
    	TextView txt = new TextView(this);
    	txt.setText("working...");
    	setContentView(txt);//we don't want a GUI here - we have either a dialog or nothing as gui
    	
    	mDialog = null;
        mDbHelper = new Database(this);
        mDbHelper.open();
        
        if(getIntent().getAction().equals(SHORTCUT_PROFILE_ACTION))
        {
        	//launch an profile

        	final long prof = getIntent().getLongExtra(SHORTCUT_PROFILE_EXTRA_ID, -1);
        	final Context c = this;
        	
        	if(prof!=-1)
        	{
        		//check if profile exists and get its state
            	Cursor notesCursor = mDbHelper.fetchProfile(prof);
	        	if(notesCursor==null)
	        	{
	        		//profile not found
	        		finish();
	        		return;
	        	}
	        	//final String name = notesCursor.getString(notesCursor.getColumnIndex(Database.P_KEY_NAME));
	        	final boolean aktive = 1==notesCursor.getInt(notesCursor.getColumnIndex(Database.P_KEY_ACTIVE));
	        	
	        	notesCursor.close();
	        	
	        	new Thread() {
                    public void run() {
			        	//Toast.makeText(c, "Switch "+name+" "+(aktive?"off":"on"), Toast.LENGTH_SHORT).show();
			        	
			        	Database DbHelper = new Database(c);
			            DbHelper.open();
			        	TimedProfiles.ToggelProfile(DbHelper, c, prof, aktive?0:1);
			        	DbHelper.close();
                    }
        		}.start();
        	}
        	//we just want to toggle - no gui
            finish();
            return;
        }
        
        if(getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT))
        {
        	final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	//show possible shortcuts

    		ListView l2 = new ListView(this);

    		l2.setOnItemClickListener(ListButtons);
    		
        	mDialog = builder.setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					finish();
				}
			}).setView(l2).setTitle(R.string.profiles).create();
    		/*
        	l2.setPadding(5, 20, 5, 20);
        	l2.setBackgroundResource(android.R.drawable.alert_light_frame);
        	l2.setDivider(getResources().getDrawable(android.R.drawable.divider_horizontal_dark));
        	setContentView(l2);*/


        	Cursor notesCursor = mDbHelper.fetchAllProfiles();
        	if(notesCursor == null)
        	{
        		Toast.makeText(this, "No Profiles", Toast.LENGTH_SHORT).show();
                finish();
                return;
        	}
        	final int in = notesCursor.getColumnIndex(Database.P_KEY_NAME),
 			ir = notesCursor.getColumnIndex(Database.P_KEY_ROWID),
 			ic = notesCursor.getColumnIndex(Database.P_KEY_ICON);
    		CharSequence[] db_name = new CharSequence[notesCursor.getCount()];
    		long[] db_id = new long[notesCursor.getCount()];
    		Drawable[] db_icon = new Drawable[notesCursor.getCount()];
    		int cnt = 0;
        	do{
        		int icon = notesCursor.getInt(ic);
        		db_name[cnt] = notesCursor.getString(in);
        		db_id[cnt] = notesCursor.getLong(ir);
        		db_icon[cnt] = getResources().getDrawable(icon==0?R.drawable.icon:icon);
        		cnt++;
        	}while(notesCursor.moveToNext() != false);
      	  notesCursor.close();
      	  
      	  l2.setAdapter(new ListAdapter(this, db_id, db_name, null, db_icon));
      	  
          return;
        }
    }
	@Override
	public void onResume()
	{
		super.onResume();
		if(mDialog!=null)
			mDialog.show();
	}
	@Override
	public void onPause()
	{
		super.onPause();
		if(mDialog!=null)
			mDialog.dismiss();
	}

    @Override
	public void onDestroy()
    {
    	mDbHelper.close();
    	super.onDestroy();
    }
   
    private OnItemClickListener ListButtons = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        	setResult(RESULT_OK, createShortCutData(v.getContext(), id, mDbHelper));
        	finish();
		}
    };
    
	public static Intent createShortCutData(Context c, long profID, Database DbHelper)
	{
		Cursor notesCursor = DbHelper.fetchProfile(profID);
		if(notesCursor==null)
		{
			Toast.makeText(c, "DB Error!", Toast.LENGTH_SHORT).show();
			return null;
		}
		//Intent that is send on click
    	Intent shortcutIntent = new Intent(c, ShortCutHandler.class);
    	shortcutIntent.setAction(SHORTCUT_PROFILE_ACTION);
    	//shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	//shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	shortcutIntent.putExtra(SHORTCUT_PROFILE_EXTRA_ID, profID);

    	//Intent to place the new shortcut
    	Intent intent = new Intent();
    	intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    	intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, notesCursor.getString(notesCursor.getColumnIndex(Database.P_KEY_NAME)));
		int icon = notesCursor.getInt(notesCursor.getColumnIndex(Database.P_KEY_ICON));
    	intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(c, icon==0?R.drawable.icon:icon));
    	intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    	notesCursor.close();
		return intent;
	}
}
